package com.platform.common.core.validator;

import com.platform.common.core.utils.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Description: 自定义枚举校验器
 * @Author: wcs
 * @Date: 2023-10-21 00:05
 **/
public class IsEnumConstraintValidator implements ConstraintValidator<IsEnum, String> {

    private IsEnum annotation;

    @Override
    public void initialize(IsEnum constraintAnnotation) {
        this.annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext context) {
        if (StringUtils.isBlank(s)) {
            return true;
        }
        Class<?>[] classes = annotation.enumClass();
        boolean flag = false;
        for (Class<?> aClass : classes) {
            if (aClass.isEnum()) {
                Enum<?>[] enumConstants = (Enum<?>[]) aClass.getEnumConstants();
                for (Enum<?> enumConstant : enumConstants) {
                    flag = s.equals(enumConstant.name());
                    if (flag) {
                        break;
                    }
                }
            }
        }
        return flag;
    }
}
